import {
  getPage
} from '../../utils/config';
import api from '../../utils/api';
import {
  http,
  promisify,
  $empty,
  $toast,
  storage,
  Validate
} from '../../utils/utils';
import wxApi from '../../utils/wxApi';
import uploadImage from '../../utils/aliyunoss/uploadAliyun';
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    content: '',
    fileList: [],
    fileList_sf: [],
    fileList_sf_f: [],
    fileList_md: [],
    mobile_tips: '请输入手机号码',
    name_tips: '请填写法人姓名',
    idno_tips: '请填写法人身份证号',
    email_tips: '请填写邮箱',
    subject_tips: '请选择证件类型',
    license_tips: '请填写营业执照号码',
    CompanyName_tips: '请填写公司/个体户名称',
    bankAccountType_tips: '请选择结算类型',
    accountName_tips: '请填写开户名称',
    accountNumber_tips:'请填写银行号码',
    bankAddressName_tips:'请选择开户银行地区',
    accountBank_tips:'请选择开户银行',
    addressForm: {
      rzname: '',
      mobile: '',
      idno: '',
      email: '',
      subject_str: '',
      subject_type: '',
      license_number: '',
      CompanyName: '',
      bank_account_str: '',
      bank_account_type: '',
      account_name: '',
      bank_name:'',
      account_bank: '',
      bank_address_name:'',
      bank_address_code:'',
      account_number:''
    },
    regionInfo: [],
    pickerArea: true,
    areaShow: false,
    pickerValue: '110101',
    areaList: {
      province_list: {},
      city_list: {},
      county_list: {},
    },
    bankList: ['工商银行', '交通银行', '招商银行', '民生银行', '中信银行', '浦发银行', '兴业银行', '光大银行', '广发银行', '平安银行', '北京银行', '华夏银行', '农业银行', '建设银行', '邮政储蓄银行', '中国银行', '宁波银行', '其他银行'],
  },
  mobileInput(e) {
    this.setData({
      mobileInputError: '',
      'addressForm.mobile': e.detail,
    });
  },
  rznameInput(e) {
    this.setData({
      ranameInputError: '',
      'addressForm.rzname': e.detail,
    });
  },
  idnoInput(e) {
    this.setData({
      idnoInputError: '',
      'addressForm.idno': e.detail,
    });
  },
  emailInput(e) {
    this.setData({
      emailInputError: '',
      'addressForm.email': e.detail,
    });
  },
  accountNameInput(e) {
    this.setData({
      accountNameInputError: '',
      'addressForm.account_name': e.detail,
    });
  },
  accountBankQtInput(e) {
    this.setData({
      'addressForm.bank_name': e.detail,
    });
  },
  licenseNumberInput(e) {
    this.setData({
      licenseInputError: '',
      'addressForm.license_number': e.detail,
    });
  },
  accountNumberInput(e) {
    this.setData({
      accountNumberError: '',
      'addressForm.account_number': e.detail,
    });
  },
  CompanyNameInput(e) {
    this.setData({
      CompanyNameInputError: '',
      'addressForm.CompanyName': e.detail,
    });
  },
  /**
   * 证件类型
   */
  subjectInput() {
    let that = this;
    wx.showActionSheet({
      itemList: ['个体户', '企业'],
      success(res) {
        if (!res.cancel) {
          let str, num;
          switch (res.tapIndex) {
            case 0:
              str = '个体户';
              num = 1;
              break;
            case 1:
              str = '企业';
              num = 2;
              break;
          }
          that.setData({
            subjectInputError: '',
            'addressForm.subject_str': str,
            'addressForm.subject_type': num,
          });

        }
      }
    });
  },
  /**
   * 证件类型
   */
  bankAccountTypeInput() {
    let that = this;
    wx.showActionSheet({
      itemList: ['对公银行账户', '经营者个人银行卡'],
      success(res) {
        if (!res.cancel) {
          let str, num;
          switch (res.tapIndex) {
            case 0:
              str = '对公银行账户';
              num = 1;
              break;
            case 1:
              str = '经营者个人银行卡';
              num = 2;
              break;
          }
          that.setData({
            bankAccountTypeInputError: '',
            'addressForm.bank_account_str': str,
            'addressForm.bank_account_type': num,
          });

        }
      }
    });
  },
  /**
   * 城市选择open || close
   */
  pickerAreaTap() {
    this.toggle('areaShow');
  },
  toggle(type) {
    this.setData({
      [type]: !this.data[type]
    });
  },
  /**
   * 确定选择城市
   */
  pickerAreaConfirm(e) {
    const {
      index,
      values
    } = e.detail;
    const {
      regionInfo
    } = this.data;
    const provice = regionInfo[index[0]];
    const city = provice.list[index[1]];
    const county = city.list[index[2]];
    this.setData({
      bankAddressCodeError: '',
      'addressForm.bank_address_name': `${provice.name} ${city.name} ${county.name}`,
      'addressForm.bank_address_code': [provice.id, city.id, county.id],
    });
    console.log(this.data.addressForm.bank_address_name);
    console.log(this.data.addressForm.bank_address_code);
    this.pickerAreaTap();
  },
  showBankList() {
    this.setData({
      bankShow: true
    })
  },
  pickerBankTap() {
    this.setData({
      bankShow: false
    })
  },
  onBankChange(e) {
    let sel_bank = e.detail.value
    this.setData({
      accountBankInputError:'',
      "addressForm.account_bank": sel_bank,
      bankShow: false
    })
  },
  deleteimg(event) {
    var index = event.detail.index;
    var fileList = this.data.fileList;
    fileList.splice(index, 1);
    this.setData({
      fileList: fileList
    });
  },
  deleteimgsf(event) {
    var index = event.detail.index;
    var fileList_sf = this.data.fileList_sf;
    fileList_sf.splice(index, 1);
    this.setData({
      fileList_sf: fileList_sf
    });
  },
  deleteimgsff(event) {
    var index = event.detail.index;
    var fileList_sf_f = this.data.fileList_sf_f;
    fileList_sf_f.splice(index, 1);
    this.setData({
      fileList_sf_f: fileList_sf_f
    });
  },
  deleteimgmd(event) {
    var index = event.detail.index;
    var fileList_md = this.data.fileList_md;
    fileList_md.splice(index, 1);
    this.setData({
      fileList_md: fileList_md
    });
  },
  afterRead(event) {
    const {
      file
    } = event.detail;
    var that = this;
    var fileList = that.data.fileList;

    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    for (var i = 0; i < file.length; i++) {
      var item = file[i];
      uploadImage({
        filePath: item.url,
        dir: "attestation",
        success(res) {
          // 上传完成需要更新 fileList

          fileList.push({
            url: api.imageCdn + res,
            picurl: res
          });
          that.setData({
            fileList: fileList
          });
        },
        fail(res) {
          $toast(`图片上传失败${JSON.stringify(res)}`);
        }
      });
    }
  },
  afterReadsf(event) {
    const {
      file
    } = event.detail;
    var that = this;
    var fileList_sf = that.data.fileList_sf;

    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    for (var i = 0; i < file.length; i++) {
      var item = file[i];
      uploadImage({
        filePath: item.url,
        dir: "attestation",
        success(res) {

          fileList_sf.push({
            url: api.imageCdn + res,
            picurl: res
          });
          that.setData({
            fileList_sf: fileList_sf
          });
        },
        fail(res) {
          $toast(`图片上传失败${JSON.stringify(res)}`);
        }
      });
    }
  },
  afterReadsff(event) {
    const {
      file
    } = event.detail;
    var that = this;
    var fileList_sf_f = that.data.fileList_sf_f;

    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    for (var i = 0; i < file.length; i++) {
      var item = file[i];
      uploadImage({
        filePath: item.url,
        dir: "attestation",
        success(res) {
          fileList_sf_f.push({
            url: api.imageCdn + res,
            picurl: res
          });
          that.setData({
            fileList_sf_f: fileList_sf_f
          });
        },
        fail(res) {
          $toast(`图片上传失败${JSON.stringify(res)}`);
        }
      });
    }
  },
  afterReadmd(event) {
    const {
      file
    } = event.detail;
    var that = this;
    var fileList_md = that.data.fileList_md;

    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    for (var i = 0; i < file.length; i++) {
      var item = file[i];
      uploadImage({
        filePath: item.url,
        dir: "attestation",
        success(res) {
          fileList_md.push({
            url: api.imageCdn + res,
            picurl: res
          });
          that.setData({
            fileList_md: fileList_md
          });
        },
        fail(res) {
          $toast(`图片上传失败${JSON.stringify(res)}`);
        }
      });
    }
  },

  /**
   * 获取code
   */
  getLoginCode() {
    return new Promise((resolve) => {
      promisify(wx.checkSession)().then(() => {
        resolve(resCode);
      }).catch(() => {
        promisify(wx.login)().then((res) => {
          resolve(res.code);
        });
      });
    });
  },
  /**
   * 提交保存
   */
  renzhengForm(e) {
    console.log('data.addressForm', this.data.addressForm)
    Validate.check(this, this.expressValidate, e.detail.value, (res) => {
      console.log('rrrrrrrrrr',res)
      if (res) {
        const data = this.data;
        const fileList = data.fileList;
        const fileList_sf = data.fileList_sf;
        const fileList_sf_f = data.fileList_sf_f;
        // const fileList_md = data.fileList_md;
        if (fileList.length == 0) {
          $toast("请上传营业执照");
          return;
        }
        if (fileList_sf.length == 0) {
          $toast("请上传身份证正面照片");
          return;
        }
        if (fileList_sf_f.length == 0) {
          $toast("请上传身份证反面照片");
          return;
        }
        const {
          shopid,
          userId,
        } = this.data;
        const {
          rzname,
          mobile,
          idno,
          email,
          subject_type,
          license_number,
          CompanyName,
          bank_account_type,
          account_name,
          bank_name,
          account_number,
          account_bank,
          bank_address_code
        } = data.addressForm;
        this.getLoginCode().then((res) => {
          const params = {
            action: 'pay_data',
            code: res,
            userid: userId,
            shopid: shopid,
            type: 'renzheng',
            RealName: rzname,
            Faren_Tel: mobile,
            IdCard: idno,
            email,
            subject_type,
            license_number,
            CompanyName,
            bank_account_type,
            account_name,
            account_number,
            bank_address_code:bank_address_code[bank_address_code.length-1],
            account_bank,
            Yingyezhizhao: fileList[0].picurl,
            IdCardPic1: fileList_sf[0].picurl,
            IdCardPic2: fileList_sf_f[0].picurl,
            // mdlist: JSON.stringify(fileList_md),
          }
          if(account_bank=='其他银行'){
            if(!bank_name) return $toast("请填写其他银行名称")
            params.bank_name = bank_name
            delete params.account_bank
          }
          if (this.data.amount == 0) {
            params.action = 'submitzizhi'
            http.post(api.default, {
              data: params
            }).then((res) => {
              if (res.data.code == 0) {
                $toast('认证成功', {
                  icon: 'success'
                });
                const pages = getCurrentPages()[getCurrentPages().length - 2];

                wx.navigateBack({
                  delta: 1,
                  success() {
                    if (pages !== undefined || pages !== null) {
                      pages.data.pageChange = 1;
                      pages.onShow();
                    }
                  }
                });
              } else {
                $toast(res.data.errmsg, {
                  icon: 'fail'
                });
              }
            })
          } else {
            // console.log('eeeeeeeeeee',params)
            // return
            http.post(api.default, {
              data: params
            }).then((res) => {
              const {
                data
              } = res.data;
              if (res.data.code == 0) {
                const {
                  sumPrice,
                  source,
                  orderId
                } = this.data;
                let result = -1;

                wx.requestPayment({
                  timeStamp: data.timeStamp,
                  nonceStr: data.nonceStr,
                  package: data.package,
                  signType: data.signType,
                  paySign: data.paySign,
                  success(e) {
                    result = 1;
                  },
                  fail(e) {
                    result = 0;
                  },
                  complete() {
                    let pages = null;

                    //如果来自我的订单或订单详情 && 付款成功
                    if (source > 0 && result == 1) {
                      pages = getCurrentPages()[getCurrentPages().length - 2];
                    }
                    wx.redirectTo({
                      url: `${getPage.paymentFeedback}?result=${result}&sumTotal=${data.orderAmount}&source=${source}&orderSn=${data.ordersn}`,
                      success() {
                        if (pages != undefined || pages != null) {
                          console.log(orderId);
                          pages.paymentUpdate(orderId);
                        }
                      }
                    });
                  }
                });
              } else {
                $toast(res.data.errmsg);
              }
            })
          }
        });
      } else {
        // $toast("请输入商品标题、价格和内容");
        this.setData({
          mobileInputError: this.data.addressForm.rzname == "" ? this.data.name_tips : '',
          ranameInputError: this.data.addressForm.mobile == "" ? this.data.mobile_tips : '',
          idnoInputError: this.data.addressForm.idno == "" ? this.data.idno_tips : '',
          emailInputError: this.data.addressForm.email == "" ? this.data.email_tips : '',
          subjectInputError: this.data.addressForm.subject_str == "" ? this.data.subject_tips : '',
          licenseInputError: this.data.addressForm.license_number == "" ? this.data.license_tips : '',
          CompanyNameInputError: this.data.addressForm.CompanyName == "" ? this.data.CompanyName_tips : '',
          bankAccountTypeInputError: this.data.addressForm.bank_account_str == "" ? this.data.subject_tips : '',
          accountNameInputError: this.data.addressForm.account_name == "" ? this.data.accountName_tips : '',
          accountNumberError: this.data.addressForm.account_number == "" ? this.data.accountNumber_tips : '',
          bankAddressCodeError: this.data.addressForm.bank_address_name == "" ? this.data.bankAddressName_tips : '',
          accountBankInputError: this.data.addressForm.account_bank == "" ? this.data.accountBank_tips : '',
        })
      }
    });

  },

  /**
   * 跳转登录
   */
  goLogin() {
    wxApi.setStartPage();
    wxApi.navigateTo(getPage.login);
  },

  /**
   * 获取地区
   */
  getRegionInfo() {
    return new Promise((resolve) => {
      storage.get('regionInfo').then((res) => {
        this.setData({
          regionInfo: res,
          pickerArea: false
        });
        resolve(res);
      }).catch((res) => {
        http.get(api.default, {
          data: {
            action: 'district'
          }
        }, false).then((res) => {
          const {
            data
          } = res.data;
          this.setData({
            regionInfo: data,
            pickerArea: false
          });
          storage.set('regionInfo', data);
          resolve(data);
        });
      });
    });
  },

  /**
   * 城市数据格式转换
   * @整体是一个 Object，包含 province_list, city_list, county_list 三个 key。
   * @每项以省市区编码作为 key，省市区名字作为 value。编码为 6 位数字，前两位代表省份，中间两位代表城市，后两位代表区县，以 0 补足 6 位。如北京编码为 11，以零补足 6 位，为 110000。
   */
  formatArea() {
    const {
      regionInfo,
      areaList
    } = this.data;
    let {
      province_list,
      city_list,
      county_list
    } = areaList;

    //一级 省份
    regionInfo.forEach((parentsItem, parentsIndex) => {
      parentsIndex = (parentsIndex + 11).toString();
      let parentsCode = parentsIndex;
      let parentsLength = parentsIndex.length;
      if (parentsLength < 6) {
        for (let i = 0; i < 6 - parentsLength; i++) {
          parentsCode = parentsCode + `0`;
        }
      }

      //二级 城市
      if (parentsItem.list.length) {
        parentsItem.list.forEach((parentItem, parentIndex) => {
          //从1开始
          parentIndex = (parentIndex + 1).toString();
          if (parentIndex < 10) {
            parentIndex = `0` + parentIndex;
          }
          parentIndex = parentsIndex + parentIndex;
          let parentCode = parentIndex;
          let parentLength = parentIndex.length;
          if (parentLength < 6) {
            for (let i = 0; i < 6 - parentLength; i++) {
              parentCode = parentCode + `0`;
            }
          }
          city_list[parentCode] = parentItem.name;

          //三级 区
          if (parentItem.list.length) {
            parentItem.list.forEach((item, index) => {
              //从1开始
              index = (index + 1).toString();
              if (index < 10) {
                index = `0` + index;
              }
              index = parentIndex + index;
              let code = index;
              let length = index.length;
              if (length < 6) {
                for (let i = 0; i < 6 - length; i++) {
                  code = code + `0`;
                }
              }
              county_list[code] = item.name
            });
          }
        });
      }
      province_list[parentsCode] = parentsItem.name;
    });

    this.setData({
      areaList
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    app.getLogin().then((res) => {
      this.setData({
        userInfo: res,
        logged: res.code,
        userId: res.data.user.user_id,
        shopid: res.data.shop.ShopId,
      });

      /**
       * 获取地区
       */
      this.getRegionInfo().then((res) => {
        //地区格式化
        this.formatArea();
        //如果修改地址
        if (this.mode) {
          const data = this.data;
          const {
            district
          } = data.addressInfo.zonedata;
          const {
            county_list
          } = data.areaList;
          Object.entries(county_list).map((key) => {
            if (district.name == key[1]) {
              this.setData({
                pickerValue: key[0],
              })
            }
          })
        }
      });
      // getzizhi   获取认证信息
      // userid  用户ID
      // shopid   店铺ID
      const params = {
        action: 'getzizhi',
        userid: res.data.user.user_id,
        shopid: res.data.shop.ShopId,
      }
      http.post(api.default, {
        data: params
      }).then(res => {
        let amount = res.data.data.amount || 0;
        console.log('res.data.data.amount===', res.data.data.amount)
        let resdata = res.data.data.info;
        console.log('resdataresdataresdata', resdata)
        this.setData({
          amount
        })
        if (resdata) {
          let zonedata = resdata.zonedata;
          let bank_address_code = [zonedata.province.id,zonedata.city.id,zonedata.district.id];
          let bank_address_name = zonedata.province.name+' '+zonedata.city.name+' '+zonedata.district.name;
          this.setData({
            'addressForm.rzname': resdata.RealName,
            'addressForm.mobile': resdata.Faren_Tel,
            'addressForm.idno': resdata.IdCard,
            'addressForm.email': resdata.email,
            'addressForm.subject_type': resdata.subject_type,
            'addressForm.subject_str': resdata.subject_type?resdata.subject_type == 1 ? '个体户' : '企业':'',
            'addressForm.license_number': resdata.license_number,
            'addressForm.account_number': resdata.account_number || '',
            'addressForm.account_name': resdata.account_name || '',
            'addressForm.account_bank': resdata.account_bank || '其他银行',
            'addressForm.bank_name':resdata.account_bank == '其他银行'? resdata.bank_name : '',
            'addressForm.bank_address_code': bank_address_code,
            'addressForm.bank_address_name': bank_address_name,
            'addressForm.CompanyName': resdata.CompanyName,
            'addressForm.bank_account_type': resdata.bank_account_type || '',
            'addressForm.bank_account_str': resdata.bank_account_type?resdata.bank_account_type == 1 ? '对公银行账户' : '经营者个人银行卡':'',
            amount,
            fileList: [{
              url: api.imageCdn + resdata.Yingyezhizhao,
              picurl: resdata.Yingyezhizhao
            }],
            fileList_sf: [{
              url: api.imageCdn + resdata.IdCardPic1,
              picurl: resdata.IdCardPic1
            }],
            fileList_sf_f: [{
              url: api.imageCdn + resdata.IdCardPic2,
              picurl: resdata.IdCardPic2
            }]
          });
        }
      })
    }).catch((res) => {
      this.setData({
        logged: res,
      });
      this.goLogin();
    });

    //获取验证规则
    Validate.rules('#mobile,#rzname,#idno,#email,#subject_str,#license_number,#CompanyName,#bank_account_str,#account_number,#bank_address_name,#account_name,#account_bank', (res) => {
      this.expressValidate = res;
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  }
})